#!/bin/bash

# 树莓派NAS配置脚本
# 适用于树莓派3B及以上版本
# 作者：AI助手
# 日期：$(date)

set -e  # 遇到错误立即退出

echo "=== 树莓派NAS配置脚本 ==="
echo "正在配置您的树莓派为NAS服务器..."

# 检查是否为root用户
if [ "$EUID" -eq 0 ]; then
    echo "错误：请不要以root用户运行此脚本"
    exit 1
fi

# 检查是否为树莓派
if ! grep -q "Raspberry Pi" /proc/cpuinfo; then
    echo "警告：此脚本专为树莓派设计"
    read -p "是否继续？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# 更新系统
echo "1. 更新系统包..."
sudo apt update && sudo apt upgrade -y

# 安装必要的软件包
echo "2. 安装NAS相关软件包..."
sudo apt install -y \
    samba \
    samba-common-bin \
    nfs-kernel-server \
    nfs-common \
    htop \
    iotop \
    smartmontools \
    hdparm \
    rsync \
    curl \
    wget \
    git \
    python3-pip \
    python3-venv \
    apache2 \
    php \
    php-mysql \
    mariadb-server \
    udev \
    ntfs-3g \
    exfat-fuse \
    exfat-utils

# 创建NAS存储目录
echo "3. 创建存储目录..."
sudo mkdir -p /mnt/nas
sudo mkdir -p /mnt/nas/public
sudo mkdir -p /mnt/nas/private
sudo mkdir -p /mnt/nas/backup
sudo mkdir -p /mnt/nas/media
sudo mkdir -p /mnt/nas/photos
sudo mkdir -p /mnt/nas/documents

# 设置目录权限
sudo chown -R pi:pi /mnt/nas
sudo chmod -R 755 /mnt/nas

# 配置Samba
echo "4. 配置Samba服务..."
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.backup

# 创建新的Samba配置
cat > /tmp/smb.conf << 'EOF'
[global]
   workgroup = WORKGROUP
   server string = Raspberry Pi NAS
   server role = standalone server
   security = user
   map to guest = bad user
   dns proxy = no
   log level = 1
   max log size = 1000
   syslog = 0
   panic action = /usr/share/samba/panic-action %d
   server signing = auto
   client signing = auto
   restrict anonymous = 2
   unix charset = UTF-8
   dos charset = CP850
   socket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=65536 SO_SNDBUF=65536
   read raw = yes
   write raw = yes
   oplocks = yes
   level2 oplocks = yes
   kernel oplocks = yes
   max xmit = 65535
   dead time = 15
   getwd cache = yes

[Public]
   comment = 公共共享
   path = /mnt/nas/public
   browseable = yes
   writable = yes
   guest ok = yes
   guest only = no
   read only = no
   create mask = 0644
   directory mask = 0755
   force user = pi
   force group = pi

[Private]
   comment = 私有共享
   path = /mnt/nas/private
   browseable = yes
   writable = yes
   guest ok = no
   valid users = pi
   create mask = 0644
   directory mask = 0755
   force user = pi
   force group = pi

[Media]
   comment = 媒体共享
   path = /mnt/nas/media
   browseable = yes
   writable = yes
   guest ok = yes
   read only = no
   create mask = 0644
   directory mask = 0755
   force user = pi
   force group = pi

[Photos]
   comment = 照片共享
   path = /mnt/nas/photos
   browseable = yes
   writable = yes
   guest ok = yes
   read only = no
   create mask = 0644
   directory mask = 0755
   force user = pi
   force group = pi

[Documents]
   comment = 文档共享
   path = /mnt/nas/documents
   browseable = yes
   writable = yes
   guest ok = no
   valid users = pi
   create mask = 0644
   directory mask = 0755
   force user = pi
   force group = pi

[Backup]
   comment = 备份共享
   path = /mnt/nas/backup
   browseable = yes
   writable = yes
   guest ok = no
   valid users = pi
   create mask = 0644
   directory mask = 0755
   force user = pi
   force group = pi
EOF

sudo cp /tmp/smb.conf /etc/samba/smb.conf

# 设置Samba用户密码
echo "5. 设置Samba用户..."
echo "请为pi用户设置Samba密码："
sudo smbpasswd -a pi

# 重启Samba服务
sudo systemctl restart smbd
sudo systemctl enable smbd

# 配置NFS
echo "6. 配置NFS服务..."
echo "/mnt/nas/public *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports
echo "/mnt/nas/media *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports
echo "/mnt/nas/photos *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports

sudo systemctl restart nfs-kernel-server
sudo systemctl enable nfs-kernel-server

# 创建Web管理界面
echo "7. 创建Web管理界面..."
sudo mkdir -p /var/www/html/nas

cat > /tmp/index.php << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>树莓派NAS管理</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            margin: 0; 
            padding: 20px; 
            background-color: #f5f5f5;
        }
        .container { 
            max-width: 1000px; 
            margin: 0 auto; 
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .content {
            padding: 20px;
        }
        .status { 
            padding: 15px; 
            margin: 15px 0; 
            border-radius: 8px; 
            border-left: 4px solid;
        }
        .online { 
            background-color: #d4edda; 
            color: #155724; 
            border-left-color: #28a745;
        }
        .offline { 
            background-color: #f8d7da; 
            color: #721c24; 
            border-left-color: #dc3545;
        }
        .info { 
            background-color: #d1ecf1; 
            color: #0c5460; 
            border-left-color: #17a2b8;
        }
        .warning {
            background-color: #fff3cd;
            color: #856404;
            border-left-color: #ffc107;
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            margin: 5px;
        }
        .btn:hover {
            background: #0056b3;
        }
        pre {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }
        .refresh-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <button class="refresh-btn" onclick="location.reload()">刷新</button>
    <div class="container">
        <div class="header">
            <h1>🍓 树莓派NAS管理面板</h1>
            <p>网络存储服务器管理系统</p>
        </div>
        
        <div class="content">
            <div class="grid">
                <div class="card">
                    <h3>📊 系统信息</h3>
                    <p><strong>主机名:</strong> <?php echo gethostname(); ?></p>
                    <p><strong>IP地址:</strong> <?php echo $_SERVER['SERVER_ADDR'] ?: $_SERVER['LOCAL_ADDR']; ?></p>
                    <p><strong>系统时间:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
                    <p><strong>运行时间:</strong> <?php echo shell_exec('uptime -p'); ?></p>
                </div>

                <div class="card">
                    <h3>💾 存储空间</h3>
                    <pre><?php echo shell_exec('df -h /mnt/nas 2>/dev/null') ?: '未挂载存储设备'; ?></pre>
                </div>
            </div>

            <div class="grid">
                <div class="status <?php echo (shell_exec('systemctl is-active smbd') == "active\n" ? 'online' : 'offline'); ?>">
                    <h3>🔄 Samba服务状态</h3>
                    <p><?php echo shell_exec('systemctl is-active smbd') == "active\n" ? '✅ 运行中' : '❌ 已停止'; ?></p>
                    <a href="smb://<?php echo $_SERVER['SERVER_ADDR'] ?: $_SERVER['LOCAL_ADDR']; ?>" class="btn">访问Samba</a>
                </div>

                <div class="status <?php echo (shell_exec('systemctl is-active nfs-kernel-server') == "active\n" ? 'online' : 'offline'); ?>">
                    <h3>🌐 NFS服务状态</h3>
                    <p><?php echo shell_exec('systemctl is-active nfs-kernel-server') == "active\n" ? '✅ 运行中' : '❌ 已停止'; ?></p>
                    <p><strong>NFS地址:</strong> <?php echo $_SERVER['SERVER_ADDR'] ?: $_SERVER['LOCAL_ADDR']; ?>:/mnt/nas/public</p>
                </div>
            </div>

            <div class="status info">
                <h3>🔗 网络连接</h3>
                <pre><?php echo shell_exec('netstat -tuln | grep -E ":(445|2049)"'); ?></pre>
            </div>

            <div class="status info">
                <h3>📁 共享目录</h3>
                <ul>
                    <li><strong>Public:</strong> /mnt/nas/public - 公共共享</li>
                    <li><strong>Private:</strong> /mnt/nas/private - 私有共享</li>
                    <li><strong>Media:</strong> /mnt/nas/media - 媒体共享</li>
                    <li><strong>Photos:</strong> /mnt/nas/photos - 照片共享</li>
                    <li><strong>Documents:</strong> /mnt/nas/documents - 文档共享</li>
                    <li><strong>Backup:</strong> /mnt/nas/backup - 备份共享</li>
                </ul>
            </div>

            <div class="status warning">
                <h3>⚠️ 访问方式</h3>
                <p><strong>Windows:</strong> \\<?php echo $_SERVER['SERVER_ADDR'] ?: $_SERVER['LOCAL_ADDR']; ?></p>
                <p><strong>Mac:</strong> smb://<?php echo $_SERVER['SERVER_ADDR'] ?: $_SERVER['LOCAL_ADDR']; ?></p>
                <p><strong>Linux:</strong> smb://<?php echo $_SERVER['SERVER_ADDR'] ?: $_SERVER['LOCAL_ADDR']; ?></p>
                <p><strong>Android:</strong> 使用ES文件管理器或Solid Explorer</p>
            </div>
        </div>
    </div>

    <script>
        // 自动刷新页面
        setTimeout(function() {
            location.reload();
        }, 30000); // 30秒刷新一次
    </script>
</body>
</html>
EOF

sudo cp /tmp/index.php /var/www/html/nas/
sudo chown -R www-data:www-data /var/www/html/nas

# 创建USB硬盘自动挂载脚本
echo "8. 创建USB硬盘自动挂载脚本..."
cat > /tmp/usb_mount.sh << 'EOF'
#!/bin/bash

DEVICE=$1
DEVICE_PATH="/dev/$DEVICE"

# 等待设备就绪
sleep 2

# 检查设备是否存在
if [ ! -b "$DEVICE_PATH" ]; then
    echo "设备 $DEVICE_PATH 不存在"
    exit 1
fi

# 获取设备信息
DEVICE_INFO=$(lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT "$DEVICE_PATH" | tail -n +2)
echo "检测到设备: $DEVICE_INFO"

# 检查是否已经挂载
if mountpoint -q /mnt/nas; then
    echo "NAS目录已经挂载"
    exit 0
fi

# 尝试挂载到NAS目录
echo "尝试挂载 $DEVICE_PATH 到 /mnt/nas"
if sudo mount "$DEVICE_PATH" /mnt/nas 2>/dev/null; then
    echo "成功挂载 $DEVICE_PATH 到 /mnt/nas"
    
    # 创建子目录
    sudo mkdir -p /mnt/nas/{public,private,backup,media,photos,documents}
    sudo chown -R pi:pi /mnt/nas
    sudo chmod -R 755 /mnt/nas
    
    # 重启服务
    sudo systemctl restart smbd
    sudo systemctl restart nfs-kernel-server
    
    echo "NAS服务已重启"
else
    echo "挂载失败，可能需要格式化设备"
fi
EOF

sudo cp /tmp/usb_mount.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/usb_mount.sh

# 创建卸载脚本
cat > /tmp/usb_umount.sh << 'EOF'
#!/bin/bash

DEVICE=$1
DEVICE_PATH="/dev/$DEVICE"

echo "卸载设备: $DEVICE_PATH"

# 检查是否挂载在NAS目录
if mountpoint -q /mnt/nas; then
    MOUNTED_DEVICE=$(df /mnt/nas | tail -1 | awk '{print $1}')
    if [ "$MOUNTED_DEVICE" = "$DEVICE_PATH" ]; then
        sudo umount /mnt/nas
        echo "已卸载 $DEVICE_PATH"
    fi
fi
EOF

sudo cp /tmp/usb_umount.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/usb_umount.sh

# 创建udev规则
cat > /tmp/99-usb-nas.rules << 'EOF'
# USB硬盘自动挂载规则
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/usr/local/bin/usb_mount.sh %k"
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/usr/local/bin/usb_umount.sh %k"
EOF

sudo cp /tmp/99-usb-nas.rules /etc/udev/rules.d/

# 重新加载udev规则
sudo udevadm control --reload-rules
sudo udevadm trigger

# 创建系统监控脚本
echo "9. 创建系统监控脚本..."
cat > /tmp/nas_monitor.sh << 'EOF'
#!/bin/bash

LOG_FILE="/var/log/nas_monitor.log"
MAX_LOG_SIZE=10485760  # 10MB

# 限制日志文件大小
if [ -f "$LOG_FILE" ] && [ $(stat -c%s "$LOG_FILE") -gt $MAX_LOG_SIZE ]; then
    mv "$LOG_FILE" "$LOG_FILE.old"
fi

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" >> $LOG_FILE
}

# 检查Samba服务
if ! systemctl is-active --quiet smbd; then
    log "Samba服务停止，正在重启..."
    systemctl restart smbd
fi

# 检查NFS服务
if ! systemctl is-active --quiet nfs-kernel-server; then
    log "NFS服务停止，正在重启..."
    systemctl restart nfs-kernel-server
fi

# 检查磁盘空间
if mountpoint -q /mnt/nas; then
    DISK_USAGE=$(df /mnt/nas | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ $DISK_USAGE -gt 90 ]; then
        log "警告：磁盘使用率超过90%"
    fi
fi

# 检查网络连接
if ! ping -c 1 8.8.8.8 >/dev/null 2>&1; then
    log "警告：网络连接异常"
fi

# 检查USB设备
USB_DEVICES=$(lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT | grep -E "sd[a-z][0-9]" | wc -l)
if [ $USB_DEVICES -eq 0 ]; then
    log "信息：未检测到USB存储设备"
fi

log "监控检查完成"
EOF

sudo cp /tmp/nas_monitor.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/nas_monitor.sh

# 添加到crontab（每5分钟检查一次）
(crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/nas_monitor.sh") | crontab -

# 创建备份脚本
echo "10. 创建备份脚本..."
cat > /tmp/nas_backup.sh << 'EOF'
#!/bin/bash

BACKUP_DIR="/mnt/nas/backup"
DATE=$(date +%Y%m%d_%H%M%S)
LOG_FILE="/var/log/nas_backup.log"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" >> $LOG_FILE
}

log "开始备份..."

# 创建备份目录
mkdir -p $BACKUP_DIR

# 备份重要配置文件
tar -czf $BACKUP_DIR/samba_config_$DATE.tar.gz /etc/samba/ 2>/dev/null
tar -czf $BACKUP_DIR/nfs_config_$DATE.tar.gz /etc/exports 2>/dev/null
tar -czf $BACKUP_DIR/system_config_$DATE.tar.gz /etc/udev/rules.d/99-usb-nas.rules /usr/local/bin/usb_mount.sh /usr/local/bin/usb_umount.sh 2>/dev/null

# 清理旧备份（保留最近7天）
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete 2>/dev/null

log "备份完成: $DATE"
EOF

sudo cp /tmp/nas_backup.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/nas_backup.sh

# 设置定时备份（每天凌晨2点）
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/nas_backup.sh") | crontab -

# 创建快速访问脚本
echo "11. 创建快速访问脚本..."
cat > /tmp/nas_status.sh << 'EOF'
#!/bin/bash

echo "=== 树莓派NAS状态 ==="
echo "主机名: $(hostname)"
echo "IP地址: $(hostname -I | awk '{print $1}')"
echo "系统时间: $(date)"
echo "运行时间: $(uptime -p)"
echo ""

echo "=== 服务状态 ==="
echo "Samba: $(systemctl is-active smbd)"
echo "NFS: $(systemctl is-active nfs-kernel-server)"
echo ""

echo "=== 存储状态 ==="
if mountpoint -q /mnt/nas; then
    df -h /mnt/nas
else
    echo "未挂载存储设备"
fi
echo ""

echo "=== USB设备 ==="
lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT | grep -E "sd[a-z]"
echo ""

echo "=== 网络连接 ==="
netstat -tuln | grep -E ":(445|2049)"
echo ""

echo "=== 访问信息 ==="
echo "Web管理: http://$(hostname -I | awk '{print $1}')/nas/"
echo "Samba: \\\\$(hostname -I | awk '{print $1}')"
echo "NFS: $(hostname -I | awk '{print $1}'):/mnt/nas/public"
EOF

sudo cp /tmp/nas_status.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/nas_status.sh

# 创建清理脚本
echo "12. 创建清理脚本..."
cat > /tmp/nas_cleanup.sh << 'EOF'
#!/bin/bash

echo "清理临时文件..."
sudo rm -rf /tmp/smb.conf /tmp/index.php /tmp/usb_mount.sh /tmp/usb_umount.sh /tmp/99-usb-nas.rules /tmp/nas_monitor.sh /tmp/nas_backup.sh /tmp/nas_status.sh /tmp/nas_cleanup.sh

echo "清理日志文件..."
sudo find /var/log -name "*.log" -size +10M -delete 2>/dev/null

echo "清理备份文件..."
find /mnt/nas/backup -name "*.tar.gz" -mtime +30 -delete 2>/dev/null

echo "清理完成"
EOF

sudo cp /tmp/nas_cleanup.sh /usr/local/bin/
sudo chmod +x /usr/local/bin/nas_cleanup.sh

# 执行清理
sudo /usr/local/bin/nas_cleanup.sh

echo ""
echo "=== 🎉 配置完成 ==="
echo ""
echo "📊 NAS状态检查："
/usr/local/bin/nas_status.sh
echo ""
echo "🌐 访问信息："
echo "- Web管理界面: http://$(hostname -I | awk '{print $1}')/nas/"
echo "- Samba共享: \\\\$(hostname -I | awk '{print $1}')"
echo "- NFS共享: $(hostname -I | awk '{print $1}'):/mnt/nas/public"
echo ""
echo "🔧 管理命令："
echo "- 查看状态: nas_status.sh"
echo "- 手动挂载USB: sudo mount /dev/sdX1 /mnt/nas"
echo "- 重启服务: sudo systemctl restart smbd nfs-kernel-server"
echo ""
echo "📝 建议的后续步骤："
echo "1. 连接USB硬盘到树莓派"
echo "2. 格式化硬盘为ext4文件系统（推荐）"
echo "3. 硬盘会自动挂载到 /mnt/nas"
echo "4. 访问Web管理界面查看状态"
echo "5. 在Windows/Mac上测试网络访问"
echo ""
echo "📋 监控日志位置："
echo "- 系统监控: /var/log/nas_monitor.log"
echo "- 备份日志: /var/log/nas_backup.log"
echo ""
echo "✅ 树莓派NAS配置完成！" 